package logic

import (
	"context"
	"fmt"
	"shop/model/cache"
	"strconv"

	"shop/shoprpc/internal/svc"
	"shop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CardListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCardListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CardListLogic {
	return &CardListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CardListLogic) CardList(in *shoprpc.CardListRequest) (*shoprpc.CardListResponse, error) {
	// todo: add your logic here and delete this line

	key := fmt.Sprintf("card:%d:*", in.UserId)
	keys, _ := cache.Rdb.Keys(l.ctx, key).Result()
	allPrice := 0.0
	var product []*shoprpc.CardList
	for _, an := range keys {
		result, _ := cache.Rdb.HGetAll(l.ctx, an).Result()
		number, _ := strconv.Atoi(result["number"])
		price, _ := strconv.ParseFloat(result["price"], 64)
		totalPrice := float64(number) * price
		allPrice += totalPrice
		list := shoprpc.CardList{
			UserId:     result["userId"],
			ProductId:  result["productId"],
			Number:     int64(number),
			Image:      result["image"],
			Title:      result["title"],
			Price:      float32(price),
			Stock:      result["stock"],
			Summit:     result["summit"],
			TotalPrice: float32(totalPrice),
		}
		product = append(product, &list)
	}

	return &shoprpc.CardListResponse{
		List:     product,
		AllPrice: float32(allPrice),
	}, nil
}
